<?php

namespace Yearnfar\Bundle\CmsBundle\Controller;

use Doctrine\ORM\Tools\Pagination\Paginator;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use Yearnfar\Bundle\CmsBundle\Entity\post;
use Yearnfar\Bundle\CmsBundle\Entity\term;

/**
 * @Route("/post")
 * @Template()
 */
class PostController extends BaseController
{
    /**
     * @Route("/")
     */
    public function indexAction()
    {
        $request = $this->get('request');

        $sort = $request->get('sort', '');
        $rows = max(1, $request->get('rows', 10));
        $page = max(1, $request->get('page', 1));

        if (strpos($sort, '_')!==false) {
            list ($sortField, $sortType) = explode('_', $sort, 2);
            $sortType = strtoupper($sortType) =='ASC' ? 'ASC' : 'DESC';

            switch ($sortField) {
                case 'aid'    :
                case 'tid'    :
                case 'publish':
                    $orderBy = " ORDER BY p.{$sortField} {$sortType},p.logtime DESC";
                    break;
                default:
                    $orderBy = " ORDER BY p.logtime {$sortType}";
                    break;
            }
        } else {
            $orderBy = " ORDER BY p.logtime DESC";
        }

        $em = $this->getDoctrine()->getManager();
        $cq = $em
            ->createQuery("SELECT p,a,t FROM CmsBundle:post p JOIN p.app a JOIN p.term t WHERE p.deltime=0".$orderBy)
            ->setFirstResult(($page-1) * $rows)
            ->setMaxResults($rows);

        $records = count(new Paginator($cq, true));
        $post    = $cq->getArrayResult();

        return [
            'post'    => $post,
            'records' => $records,
            'page'    => $page,
            'total'   => ceil($records/$rows),
            'sort'    => $sort,
        ];
    }

    /**
     * @Route("/view")
     */
    public function viewAction()
    {
        $request = $this->get('request');
        $pid = $request->get('pid');

        $em = $this->getDoctrine()->getManager();
        $op = $em->find('CmsBundle:post', $pid);

        $post = ['title'=>'', 'logtime'=>0, 'content'=>'', 'term'=>['pid'=>0]];
        if ($op) {
            $post = $op;
            $tid = $post->getTerm()->getIdentify();

            switch ($tid) {
                //手游攻略站预览
                case 'raider_instroduce':
                case 'raider_novice':
                case 'raider_advance':
                case 'raider_checkpoint':
                case 'raider_combination':
                case 'raider_hunter':
                    return $this->render('CmsBundle:Post:view_raider.html.twig', ['post'=>$post]);
                //端游视频预览
                case 'video_animation':
                    return $this->render('CmsBundle:Post:view_video1.html.twig', ['post'=>$post]);
                //手游视频预览
                case 'video_publicize':
                case 'video_instroduce':
                case 'video_school':
                    return $this->render('CmsBundle:Post:view_video2.html.twig', ['post'=>$post]);
                case 'raider2_play':
                case 'raider2_profession':
                case 'raider2_skill':
                case 'raider2_weapon':
                    return $this->render('CmsBundle:Post:view_raider2.html.twig', ['post'=>$post]);
                default:
                    break;
            }
        }

        return ['post'=>$post];
    }

    /**
     * @Route("/viewport")
     */
    public function viewportAction()
    {
        $pid = $this->get('request')->get('pid');
        return ["pid" => $pid];
    }

    /**
     * @Route("/edit")
     */
    public function editAction()
    {
        $request = $this->get('request');
        $submit  = $request->get('submit');
        $pid     = $request->get('pid', 0);
        $sort = $request->get('sort', '');
        $page = max(1, $request->get('page', 1));

        //跳转URL
        $backUrl = "/cms/post/?sort={$sort}&page={$page}";

        $em = $this->getDoctrine()->getManager();
        $current = $pid>0 ? $em->find('CmsBundle:post', $pid) : new post();

        if ($submit) {
            $aid = $request->get('aid');
            $tid = $request->get('tid');
            $author = $request->get('author', '');
            $title  = $request->get('title');
            $cover  = $request->get('cover');
            $content = $request->get('content');
            $publish = $request->get('publish');
            //
            $app  = $em->find('CmsBundle:app', $aid);
            $term = $em->find('CmsBundle:term', $tid);

            $current
                ->setApp($app)
                ->setTerm($term)
                ->setAuthor($author)
                ->setCover($cover)
                ->setTitle($title)
                ->setContent($content)
                ->setPublish($publish ? 1 : 0)
                ->setDeltime(0);

            if ($pid<=0) {
                $current->setLogtime(time());
            }

            $em->persist($current);
            $em->flush();

            if ($pid>0) {
                return $this->msgOut('修改文章成功!', $backUrl);
            }
            return $this->msgOut('添加文章成功！', $backUrl);
        }

        $app  = $em->getRepository('CmsBundle:app')->findAll();
        $term = $em->getRepository('CmsBundle:term')->findAll();

        $callBack = function (&$result, $pid=0, $depth=-1) use (&$callBack, $term) {
            $depth++;
            foreach ($term as $ot) {
                if ($ot->getPid()==$pid) {
                    $ot->name2 = str_repeat('——', $depth). $ot->getName();

                    $result[] = $ot;
                    $callBack($result, $ot->getId(), $depth);
                }
            }
        };

        $_term = [];
        $callBack($_term);

        $timestamp  = time();
        $token = md5('unique_salt'.$timestamp);

        return [
            'current'  => $current,
            'app'      => $app,
            'term'     => $_term,
            'timestamp'=> $timestamp,
            'token'    => $token,
            'page'     => $page,
            'sort'     => $sort,
        ];
    }

    /**
     * @Route("/delete")
     */
    public function deleteAction()
    {
        $request = $this->get('request');
        $_pid = $request->get('pid');
        $sort = $request->get('sort', '');
        $page = max(1, $request->get('page', 1));

        //跳转URL
        $backUrl = "/cms/post/?sort={$sort}&page={$page}";

        foreach(explode(',', $_pid) as $_id) {
            if (is_numeric($_id)) {
                $pid[] = $_id;
            }
        }

        if (empty($pid)) {
            return $this->msgOut('请选择需要删除的文章！', $backUrl);
        }

        $pid = implode(',', $pid);
        $em = $this->getDoctrine()->getManager();
        $affectNum = $em
            ->createQuery("UPDATE CmsBundle:post p SET p.deltime=".time().", p.publish=0 WHERE p.id IN(". $pid .")")
            ->getResult();

        if ($affectNum>0) {
            return  $this->msgOut("删除文章成功！", $backUrl);
        } else {
            return $this->msgOut('文章不存在！', $backUrl);
        }
    }

    /**
     * @Route("/recycle")
     */
    public function recycleAction()
    {
        $request = $this->get('request');

        $rows = max(1, $request->get('rows', 10));
        $page = max(1, $request->get('page', 1));

        $em = $this->getDoctrine()->getManager();
        $cq = $em
            ->createQuery("SELECT p,a,t FROM CmsBundle:post p JOIN p.app a JOIN p.term t WHERE p.deltime>0 ORDER BY p.deltime DESC")
            ->setFirstResult(($page-1) * $rows)
            ->setMaxResults($rows);

        $records = count(new Paginator($cq, true));
        $post    = $cq->getArrayResult();

        return [
            'post'    => $post,
            'records' => $records,
            'page'    => $page,
            'total'   => ceil($records/$rows),
        ];
    }

    /**
     * @Route("/undo")
     */
    public function undoAction()
    {
        $request = $this->get('request');
        $_pid = $request->get('pid');

        foreach(explode(',', $_pid) as $_id) {
            if (is_numeric($_id)) {
                $pid[] = $_id;
            }
        }

        if (empty($pid)) {
            return $this->msgOut('请选择需要还原的文章！', '/cms/post/recycle');
        }

        $pid = implode(',', $pid);
        $em = $this->getDoctrine()->getManager();
        $affectNum = $em
            ->createQuery("UPDATE CmsBundle:post p SET p.deltime=0, p.publish=0 WHERE p.id IN(". $pid .")")
            ->getResult();

        if ($affectNum>0) {
            return  $this->msgOut("恢复成功！", '/cms/post/recycle');
        } else {
            return $this->msgOut('文章不存在！', '/cms/post/recycle');
        }
    }

    /**
     * @Route("/delete2")
     */
    public function delete2Action()
    {
        $request = $this->get('request');
        $_pid = $request->get('pid');

        foreach(explode(',', $_pid) as $_id) {
            if (is_numeric($_id)) {
                $pid[] = $_id;
            }
        }

        if (empty($pid)) {
            return $this->msgOut('请选择需要删除的文章！', '/cms/post/recycle');
        }

        $pid = implode(',', $pid);
        $em = $this->getDoctrine()->getManager();
        $affectNum = $em
            ->createQuery("DELETE CmsBundle:post p WHERE p.id IN(". $pid .")")
            ->getResult();

        if ($affectNum>0) {
            return $this->msgOut('删除成功！', '/cms/post/recycle');
        } else {
            return $this->msgOut('文章不存在！', '/cms/post/recycle');
        }
    }

}
